import 'package:flutter/material.dart';
import 'package:flutter_lui/flutter_lui.dart';

/// 用于在子widget渲染完成后，执行回调 返回子组件的屏幕位置和尺寸
class LPostFrameInfo extends StatefulWidget {
  final Widget child;
  final Function(LPostFrameInfoValue) callback;
  const LPostFrameInfo({required this.child, required this.callback, Key? key})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _LPostFrameInfo();
}

class _LPostFrameInfo extends State<LPostFrameInfo> {
  final GlobalKey _key = GlobalKey();
  LPostFrameInfoValue? v;
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback(getWidgetInfo);
    super.initState();
  }

  @override
  void didUpdateWidget(LPostFrameInfo oldWidget) {
    super.didUpdateWidget(oldWidget);
    delay(100).then((value) => getWidgetInfo(1));
  }

  getWidgetInfo(_) {
    RenderBox? box = _key.currentContext?.findRenderObject() as RenderBox?;
    if (box != null) {
      var size = box.size;
      var position = box.localToGlobal(Offset.zero);
      var value = LPostFrameInfoValue(
          size.width, size.height, position.dx, position.dy);
      value.width;

      if (v?.width != value.width ||
          v?.hieght != value.hieght ||
          v?.globalx != value.globalx ||
          v?.globaly != value.globaly) {
        v = value;
        widget.callback(value);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(key: _key, child: widget.child);
  }
}

class LPostFrameInfoValue {
  final double width;
  final double hieght;
  final double globalx;
  final double globaly;
  LPostFrameInfoValue(this.width, this.hieght, this.globalx, this.globaly);

  @override
  String toString() {
    return 'LPostFrameInfoValue(\n{\n  width: $width,\n  hieght: $hieght, \n  globalx: $globalx, \n  globaly: $globaly\n})';
  }
}
